import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from './index.less';
import { Empty } from 'antd';
import echarts from 'echarts/lib/echarts';
// import * as echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'; //折线图
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip'; //提示框
import 'echarts/lib/component/title'; //标题
import 'echarts/lib/component/legend'; //图例
import 'echarts/lib/component/legendScroll'; //图例

/**
 * 折线图
 * @param props
 * @returns {*}
 * @constructor
 */
class RcLineChart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      myEchart: null,
      noData: false, //是否无数据
      yNewAxis: {
        type: 'value',
        nameTextStyle: {
          color: '#9497AA',
          fontSize: this.props.yAxis.fontSize || null, //Y轴单位的字体大小
          padding: this.props.yAxis.padding || null, //Y轴单位的字体大小
        },
        axisTick: {
          //y轴刻度线
          show: this.props.YaxisTick,
        },
        axisLabel: {
          show: this.props.axisLabelLineShow,
          inside: this.props.yAxis.inside || false, //Y轴的数是否朝内显示
          verticalAlign: this.props.yAxis.inside || false ? 'bottom' : 'center',
          textStyle: {
            color: '#9497AA',
            fontSize: this.props.fontSize,
          },
        },
        splitLine: {
          show: this.props.lineShow,
          lineStyle: {
            color: '#e7eaed',
          },
        },
        axisLine: {
          show: this.props.lineShow,
          lineStyle: {
            color: '#e7eaed',
          },
        },
      },
      grid: {
        top: '20%',
        left: '0%',
        right: '0%',
        bottom: '0%',
        containLabel: true,
      },
      mapOpacity: 0,
    };
  }

  componentDidMount() {
    this.setState(
      {
        myEchart: echarts.init(window.document.getElementById(this.props.id)),
      },
      () => {
        window.addEventListener('resize', () => {
          this.state.myEchart.resize();
        });
        this.state.myEchart.showLoading({ text: '数据加载中' });
        this.state.myEchart.on('click', (data) => {
          this.props.click && this.props.click(data);
        });
        //解决当 echarts 节点是 有数据后再挂载节点的问题  手动触发 props更新
        if (this.props.isSuccess) {
          this.componentWillReceiveProps(this.props);
        }
      },
    );
  }

  componentWillUnmount() {
    window.clearInterval(this.inter);
  }

  componentWillReceiveProps(nextProps) {
    // if (nextProps.yData === this.props.yData && this.props.yData.length > 0 && nextProps.xData === this.props.xData && this.props.xData.length > 0) {
    //   return;
    // }
    if (!nextProps.isSuccess) {
      return;
    }
    if (
      JSON.stringify(nextProps.yData) === JSON.stringify(this.props.yData) &&
      JSON.stringify(nextProps.xData) === JSON.stringify(this.props.xData)
    ) {
      return;
    }
    if (nextProps.xData.length > 0 && nextProps.yData.length > 0) {
      this.setState(
        {
          noData: false,
          yData: nextProps.yData,
        },
        () => {
          this.state.myEchart.clear();
          // 轮询折线点
          let index = 0;
          this.inter = setInterval(() => {
            this.state.myEchart.dispatchAction({
              type: 'showTip',
              seriesIndex: 0,
              dataIndex: index,
            });
            index++;
            if (index > xData.length) {
              index = 0;
            }
          }, 3000);
          this.state.myEchart.hideLoading();
          let {
            id,
            xData,
            yData,
            legendName,
            title,
            stack,
            barWidth,
            legendLength,
            yAxis,
            grid,
            color,
            legendShow,
          } = nextProps;
          this.setEcharts(
            id,
            xData,
            yData,
            legendName,
            title,
            stack,
            barWidth,
            legendLength,
            yAxis,
            grid,
            color,
            legendShow,
          );
        },
      );
    } else {
      this.setState(
        {
          noData: true,
        },
        () => {
          this.state.myEchart.clear();
          this.state.myEchart.hideLoading();
        },
      );
    }
  }

  setEcharts = (
    id,
    xData,
    yData,
    legendName,
    title,
    stack,
    barWidth,
    legendLength,
    yAxis,
    grid,
    color,
    legendShow,
  ) => {
    let seriesData = [];
    let newGrid = Object.assign(this.state.grid, grid);
    let legendSelected = {},
      yNewAxiss = {};
    if (legendLength) {
      legendName.forEach((item, index) => {
        if (index + 1 > legendLength) {
          legendSelected[item] = false;
        }
      });
    }
    yNewAxiss = Object.assign(yAxis, this.state.yNewAxis);
    let option = {
      title: {
        text: title,
        subtext: 'KVA',
        left: 5, // 距离左边位置
        top: 0, // 距离上面位置
        padding: [10, 0, 0, 10],
        textStyle: {
          color: '#000',
          fontWeight: 'normal',
          fontSize: 16,
        },
      },
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        show: legendShow,
        width: '70%',
        type: 'scroll',
        data: legendName,
        x: this.props.legendTextPosition,
        padding: this.props.legendPadding,
        selected: legendSelected,
        textStyle: { color: this.props.legendTextColor },
        selectedMode: this.props.isClick,
        icon: 'circle',
        itemWidth: 10, // 设置宽度
        itemHeight: 10, // 设置高度
        itemGap: 20, // 设置间距
      },
      grid: newGrid,
      xAxis: [
        {
          type: 'category',
          data: xData,
          boundaryGap: false,
          axisLabel: {
            //坐标轴刻度标签的相关设置。
            show: true,
            textStyle: {
              color: '#9497AA',
              fontSize: this.props.fontSize,
            },
            rotate: this.props.rotate,
            interval: this.props.interval,
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            lineStyle: {
              color: '#e7eaed',
            },
            show: this.props.lineShow,
          },
        },
      ],
      yAxis: yNewAxiss,
      series: [
        {
          name: '有功功率',
          type: 'line',
          stack: stack,
          data: this.state.yData[0],
          barWidth: barWidth, //柱图宽度
          animation: true, // 是否开启动画
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          smooth: true,
          areaStyle: {
            normal: {
              color: {
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(80,203,116,0.44)', // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: 'rgba(136,231,172,0)', // 100% 处的颜色
                  },
                ],
                globalCoord: false, // 缺省为 false
              },
            },
          },
        },
        {
          name: '视在功率',
          type: 'line',
          stack: stack,
          data: this.state.yData[1],
          barWidth: barWidth, //柱图宽度
          animation: true, // 是否开启动画
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          smooth: true,
          areaStyle: {
            normal: {
              color: {
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(45,140,240,0.2)', // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: 'rgba(89,192,249,0)', // 100% 处的颜色
                  },
                ],
                globalCoord: false, // 缺省为 false
              },
            },
          },
        },
      ],
    };
    if (color && color.length == legendName.length) {
      option.color = color;
    }
    this.state.myEchart.setOption(option);
    this.state.myEchart.hideLoading();
    this.setState({
      mapOpacity: 1,
    });
  };

  render() {
    return (
      <div className={styles.rcpiechart}>
        <div
          id={this.props.id}
          style={{
            width: '100%',
            height: '100%',
            opacity: this.state.mapOpacity,
          }}
        ></div>
        {this.state.noData && (
          <div className={styles.rcempty}>
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
          </div>
        )}
      </div>
    );
  }
}

/*需要的参数*/
RcLineChart.propTypes = {
  stack: PropTypes.bool, //每一条数据是否是叠加在一起的
  legendLength: PropTypes.number, //图例显示的个数
  id: PropTypes.string.isRequired, //id
  xData: PropTypes.array.isRequired, //x轴刻度值
  yData: PropTypes.array.isRequired, //数据
  legendName: PropTypes.array, //图例名称
  legendShow: PropTypes.bool, //图例是否显示
  title: PropTypes.string, //标题
  yAxis: PropTypes.object, // Y轴的设置
  grid: PropTypes.object,
  click: PropTypes.func, //点击事件
  color: PropTypes.array, //颜色
  isSuccess: PropTypes.bool.isRequired, //是否成功拿到了数据
  lineShow: PropTypes.bool, //是否展示网格线及x轴标识
  legendTextColor: PropTypes.string, //图例名称颜色
  legendTextPosition: PropTypes.string, //图例名称显示的位置
  axisLabelLineShow: PropTypes.bool, //是否暂时左侧刻度
  isClick: PropTypes.bool, //图例是否可点击
  legendPadding: PropTypes.array, //图例的padding值
  rotate: PropTypes.number, //图例x轴倾斜
  fontSize: PropTypes.number, //x轴显示字体的大小
  YaxisTick: PropTypes.bool, //y轴刻度线是否展示
  interval: PropTypes.number, //x轴 隔几个展示一个
};

/*参数的默认值*/
RcLineChart.defaultProps = {
  legendShow: true,
  id: 'line',
  title: '',
  legendName: [],
  stack: false, //每一条数据是否是叠加在一起的
  barWidth: 20, //柱图每一条柱子的宽度
  yAxis: {
    //echarts的yAxis属性均可传入
  },
  grid: {},
  isSuccess: false,
  lineShow: true,
  legendTextColor: 'black',
  legendTextPosition: 'right',
  axisLabelLineShow: true,
  isClick: true,
  legendPadding: [10, 20, 0, 0],
  rotate: 0,
  fontSize: 14,
  YaxisTick: true,
  interval: 1,
};

export default RcLineChart;
